#!/usr/bin/env bash
# 本脚本用于安装最新版本nexus3
# auther: devops-xu
# date: 2021-07-02

CheckNexusEnv(){
  # check user for nexus
  if id -u nexus > /dev/null 2>&1;then
    echo "user nexus is exist"
  else
    echo "nexus user does not exist, start creating nexus user."
    sleep 1
    useradd nexus
    echo "nexus user is ready"
  fi

  # check java environments
  which java
  if [ $? -eq 0 ];then
    echo "java environments is ready"
  else
    yum -y install java-1.8.0-openjdk
  fi

  # check for ulimit

  if [ `su nexus -c 'ulimit -n'` -lt 65535 ];then
    cat >>/etc/security/limits.conf <<EOF
    nexus soft nofile 100001
    nexus hard nofile 100002
EOF
  else
    echo "ulimit is `su nexus -c 'ulimit -n'`"
  fi
}

DeployNexus(){
  mkdir /opt/nexus_3.31.0_home
  cd /opt/nexus_3.31.0_home
  # 网络不好的话，就只能多试试了
  wget https://sonatype-download.global.ssl.fastly.net/repository/downloads-prod-group/3/nexus-3.31.0-01-unix.tar.gz
  if [ ! -f nexus-3.31.0-01-unix.tar.gz ];then
    echo "nexus 部署包下载失败，请重新尝试"
    exit 1
  fi
  tar zvxf nexus-3.31.0-01-unix.tar.gz
  # 修改nexus启动用户
  sed -i 's/#run_as_user=\"\"/run_as_user=\"nexus\"/g' /opt/exus_3.31.0_home/nexus-3.31.0-01/bin/nexus.rc
  # 修改文件属组为nexus
  chown -R /opt/exus_3.31.0_home
  /opt/exus_3.31.0_home/nexus-3.31.0-01/bin/nexus start

  while true
  do
    if [ -f /opt/exus_3.31.0_home/sonatype-work/nexus3/admin.password ];then
      echo "nexus 已启动"
      echo "请通过浏览器访问 http://`ifconfig| grep broadcast | awk '{print $2}'`:8081 访问nexus"
      echo "nexus admin账号密码为：`cat /opt/exus_3.31.0_home/sonatype-work/nexus3/admin.password`"
      break
    else
      echo "nexus is startings ..."
      sleep 3
    fi
  done
}




main(){
  CheckNexusEnv
  DeployNexus
}


main
